﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Drawing;
using CarInfoDBAccess;
using System.Windows.Media.Animation;

namespace CarInfoSpider
{
   

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        #region  启动,初始化,按钮事件
        BackgroundWorker bw;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //List<CarInfoDBAccess.Model.Brand> temp = CarInfoDBAccess.Operation.GetAllInfoFormDB().ToList();
            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(Do_Work);
            bw.WorkerReportsProgress = true;
            bw.ProgressChanged += new ProgressChangedEventHandler(Report_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

            
            CarInfoBusiness.Common.Instance.RegTextOutput(ApendText2TextBox);
            CarInfoBusiness.Common.Instance.RegProcesssBarValue(ChangeProgress);

        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (this.txtBrandLimited.Text.Length != 0)
                CarInfoBusiness.GetCarBrands.Instance.MaxBrandsLimit = Convert.ToInt32(this.txtBrandLimited.Text.Trim());

            this.btnStart.IsEnabled = false;
            this.pbDetails.Value = 0;

            bw.RunWorkerAsync();

        }

        private void btnAbort_Click(object sender, RoutedEventArgs e)
        {
            if (bw.IsBusy)
            {
                bw.CancelAsync();
            }
        }



        #endregion

        #region 消息显示
        

        private void ApendText2TextBox(string msg)
        {
            if (System.Threading.Thread.CurrentThread != this.txtDetails.Dispatcher.Thread)
                this.txtDetails.Dispatcher.Invoke(new CarInfoBusiness.Append2Text(ApendText2TextBox), msg + " !");
            else
            {
                this.txtDetails.AppendText(string.Format("[{0}] {1}\r\n", DateTime.Now.ToString("HH:mm:ss"), msg));
                //if(this.txtDetails
                this.txtDetails.ScrollToEnd();
            }
        }

        #endregion

        #region BackgroundWorker工作

        private void Do_Work(object sender, DoWorkEventArgs e)
        {


            ApendText2TextBox("Initialization...");
            
            
            brands = CarInfoBusiness.GetCarBrands.Instance.GetBrands("http://db.chinacars.com/Brand.shtml");
            if (brands != null)
            {
                ApendText2TextBox("GetBrands Finished!");
                
                ChangeProgress(CarInfoBusiness.CalcProgressBar.Instance.GetBrandsFinished(brands.Count));
                int brandscount = 1;
                foreach (var brand in brands)
                {
                    List<CarInfoDBAccess.DBAccess_New.CSCarType> ctList=CarInfoBusiness.GetCarTypes.Instance.GetTypes(brand);
                    foreach (var item in ctList)
                    {
                        brand.CSCarType.Add(item);
                    }
                    int typescount = 1;
                    if (brand.CSCarType != null)
                        foreach (var type in brand.CSCarType)
                        {
                            List<CarInfoDBAccess.DBAccess_New.CSCarInfo> ciList = CarInfoBusiness.GetInfos.Instance.GetCar(type);
                            foreach (var item in ciList)
                            {
                                type.CSCarInfo.Add(item);
                            }
                            ChangeProgress(CarInfoBusiness.CalcProgressBar.Instance.GetTypeFinished(typescount, brand.CSCarType.Count, brandscount));
                            typescount++;
                        }
                    brandscount++;
                    DBAccess.Instance.Save2DB(brand);
                }
                //DBAccess.Instance().Save2DB(brands);
                //CarInfoDBAccess.Operation.Instance.Save2DB(brands.ToArray());
               // CarStoreDB.DBAccess.Instance().Save2DB(brands);
                ApendText2TextBox("Finished");
            }
            else
            {
                ApendText2TextBox("GetBrands Failed!");
            }

        }

        private void Report_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.pbDetails.Value = (double)e.UserState;
            Duration duration = new Duration(TimeSpan.FromSeconds(1));
            DoubleAnimation doubleanimation = new DoubleAnimation((double)e.UserState, duration);
            pbDetails.BeginAnimation(ProgressBar.ValueProperty, doubleanimation);
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.btnStart.IsEnabled = true;
        }

        private void ChangeProgress(double value)
        {
            bw.ReportProgress(0, value);
        }

        private void ChangeProgress(int value)
        {
            ChangeProgress((double)value);
        }
        #endregion

        List<CarInfoDBAccess.DBAccess_New.CSBrand> brands;

        private void txtBrandLimited_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                double num = 0;
                if (!Double.TryParse(textBox.Text, out num))
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);

                }
            }
        }


    }
}
